<?php
namespace app\shouyin\admin;
use app\system\admin\Admin;
use app\product\model\Product as ProductModel;
use app\system\model\systemUser as systemUserModel;
use app\finance\model\Account as AccountModel;
use app\warehouse\model\Warehouse as WarehouseModel;
use think\Db;
use think\Cache;
class ProductOrderGoods extends Admin
{
    protected $hisiModel = 'ProductOrderGoods';//模型名称[通用添加、修改专用]
    protected $hisiTable = '';//表名称[通用添加、修改专用]
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    protected function initialize()
    {
        parent::initialize();
        if ($this->request->action() != 'index' && !$this->request->isPost()) {
            // 会员
            $products = ProductModel::getSelect(ProductModel::all());
            $this->assign('products', $products);
            $technicians = systemUserModel::getSelect(systemUserModel::where('shop_id',session('shop_id'))->where('type',7)->all());
            $this->assign('technicians', $technicians);
            $advisers = systemUserModel::getSelect(systemUserModel::where('shop_id',session('shop_id'))->where('type',5)->all());
            $this->assign('advisers', $advisers);
            $account = AccountModel::getSelect(AccountModel::all());
            $this->assign('accounts',$account);
            $warehouses = WarehouseModel::getSelect(WarehouseModel::where('shop_id',session('shop_id'))->all());
            $this->assign('warehouses',$warehouses);
        }
    }

    public function index()
    {
        return $this->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {

            $postData = $this->request->post();

            if ($this->hisiModel) {// 通过Model添加
                // halt();
                if(Db::name('product_order')->where('sn',$postData['sn'])->find()){
                    $model = $this->model();

                    if (!$model->save($postData)) {
                        return $this->error($model->getError());
                    }
                }else{
                    $arr[] = $postData;
                    if(!cache($postData['sn'],$arr)){
                        return $this->error('保存出错，请联系管理员');
                    }
                }

            } else if ($this->hisiTable) {// 通过Db添加

                if (!Db::name($this->hisiTable)->insert($postData)) {
                    return $this->error('保存失败');
                }

            } else {

                return $this->error('当前控制器缺少属性（hisiModel、hisiTable至少定义一个）');

            }

            return $this->success('保存成功', '');
        }

        $template = $this->request->param('template', 'form');
        $sn = $this->request->param('sn');
        $this->assign('sn',$sn);
        // halt($sn);
        return $this->fetch($template);
    }
}
